#include <QTcpSocket>
#include <QDebug>
#include <QTcpServer>
#include <QFileDialog>
#include <QMessageBox>
#include <QThread>
#include "recvfile.h"
#include <QHostAddress>
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this); 
    ui->lineEdit_port->setText("7777"); 
    this->lfd = new QTcpServer(this); 

    // 启动监听  
    connect(ui->btn_listen, &QPushButton::clicked, this, [=]()
    {
        unsigned short port = ui->lineEdit_port->text().toUShort(); 
        this->lfd->listen(QHostAddress::Any, port); 
        ui->btn_listen->setEnabled(false); 
    }); 
    
    // 接收到新的连接 
    connect(lfd, &QTcpServer::newConnection, this, [=]()
    {
        qDebug() << "new Connection"; 
        QTcpSocket *cfd = lfd->nextPendingConnection(); 
        RecvFile *t = new RecvFile(cfd); 
        t->start(); 

        // 无法打开文件 
        connect(t, &RecvFile::openfile_error, this, [=]()
        {
            QMessageBox::warning(this, "写入文件失败", "!!!!!"); 
        }); 

        // 接收子线程接收完毕的信号 
        connect(t, &RecvFile::recv_ok, this, [=]()
        {
            //QMessageBox::information(this, "文件接收成功", "文件接收完毕"); 
            //ui->btn_listen->setEnabled(true); 
            qDebug() << "recv_ok"; 
        }); 

        // 接收断开信号 
        connect(t, &RecvFile::disconnect, this, [=]()
        {
            cfd->close(); 
            t->quit(); 
            t->wait(); 
            cfd->deleteLater(); 
            t->deleteLater();
            QMessageBox::information(this, "断开", "与客户端断开连接"); 
        }); 
    }); 
}

MainWindow::~MainWindow()
{
    delete ui;
}
